#include "StdAfx.h"
#include "XmlDbParser.h"
#include "qxmlstream.h"

XmlDbParser::XmlDbParser()
{
}

XmlDbParser::~XmlDbParser()
{
}

bool XmlDbParser::parse( const QString & sourceData )
{
    m_sourceData = sourceData;
    m_parseResult.reset();
    QXmlStreamReader xmlStreamReader( sourceData );
    if (xmlStreamReader.hasError())
        return false;

    QXmlStreamReader::TokenType token;
    QString elementName, value;
    while (! xmlStreamReader.atEnd())
    {
		token = xmlStreamReader.readNext();
		if(token == QXmlStreamReader::StartDocument) 
			continue;
	
        if (token == QXmlStreamReader::EndElement)
            return true;

		if (token != QXmlStreamReader::StartElement)
            return false;

        elementName = xmlStreamReader.name().toString();
        if (token == QXmlStreamReader::StartElement)
        {
            if (elementName == "data")
            {
                if (xmlStreamReader.readNext() != QXmlStreamReader::StartElement)
                    return false;

                elementName = xmlStreamReader.name().toString();
            }
        }

        token = xmlStreamReader.readNext();
        if (token != QXmlStreamReader::Characters)
            return false;

        QString value = xmlStreamReader.text().toString();

        token = xmlStreamReader.readNext();
        if (token != QXmlStreamReader::EndElement)
            return false;

		if(elementName == "queryError")
        {
            m_parseResult.queryErrorString = value;
		}
		else if(elementName == "sessionId") 
        {
            m_parseResult.sessionId = value.toUtf8();
		}
        else if(elementName == "logged") 
        {
            bool ok = false;
			int s = value.toInt( & ok );
            if (ok && ( s >= 0 && s <= 4 ))
                m_parseResult.sessionStatus = (SessionLoggedStatus::Enum)s;
		}
        else if (elementName == "queryResult") 
        {
			m_parseResult.queryResult = value.toUtf8();
		}
        else
        {
            return false;
        }
		
	}

    return true;
}

const ParseResult & XmlDbParser::parseResult() const
{
    return m_parseResult;
}